#include <map>
#include "minimap.h"
#include "functions.h"
#include "globals.h"

Minimap::Minimap()
{
    box.x = 0;
    box.y = 0;
    box.w = 0;
    box.h = 0;

    cam.x = 0;
    cam.y = 0;
    cam.w = 0;
    cam.h = 0;
}

void Minimap::setup()
{
    box.w = cfg.get_minimap_width();
    box.h = cfg.get_minimap_height();
    box.x = 8;
    box.y = cfg.get_screen_height() - box.h - 8;

    cam.w = (float)cfg.get_screen_width() / cfg.get_map_width() * box.w;
    cam.h = (float)cfg.get_screen_height() / cfg.get_map_height() * box.h;
}

void Minimap::draw()
{
    // Draw background
    draw_box(box.x, box.y, box.w, box.h, 0x777777CC, true, false);

    // Draw NPCs
    for (std::map<int, Npc*>::iterator i = Npcs.begin(); i != Npcs.end(); i++)
    {
        Npc* npc = i->second;
        draw_box(((float)npc->x() / cfg.get_map_width()) * box.w + box.x - 1, ((float)npc->y() / cfg.get_map_height()) * box.h + box.y - 1, 2, 2, 0xFF0000FF, true, false);
    }

    // Draw other players
    for (std::map<RakNet::RakNetGUID, Player*>::iterator i = Players.begin(); i != Players.end(); i++)
    {
        Player* player = i->second;
        draw_box(((float)player->x() / cfg.get_map_width()) * box.w + box.x - 1, ((float)player->y() / cfg.get_map_height()) * box.h + box.y - 1, 2, 2, 0x00FF00FF, true, false);
    }

    // Draw myplayer
    draw_box(((float)P.x() / cfg.get_map_width()) * box.w + box.x - 1, ((float)P.y() / cfg.get_map_height()) * box.h + box.y - 1, 2, 2, 0xFFFFFFFF, true, false);

    // Draw camera
    draw_box(cam.x, cam.y, cam.w, cam.h, 0xFFFFFFFF, false, false);

    // Draw outlines
    draw_box(box.x, box.y, box.w, box.h, 0x000000FF, false, false);
}

void Minimap::update_camera(position camera)
{
    cam.x = xToMap(camera.x);
    cam.y = yToMap(camera.y);
}

float Minimap::xToMap(float x)
{
    return x / cfg.get_map_width() * box.w + box.x;
}

float Minimap::yToMap(float y)
{
    return y / cfg.get_map_height() * box.h + box.y;
}

float Minimap::mapToX(float x)
{
    return (x - box.x) / box.w * cfg.get_map_width();
}

float Minimap::mapToY(float y)
{
    return (y - box.y) / box.h * cfg.get_map_height();
}

SDL_Rect Minimap::get_box()
{
    return box;
}

SDL_Rect Minimap::get_cam()
{
    return cam;
}
